package com.v1.video.pay;

import java.io.StringReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import com.tencent.mm.sdk.modelpay.PayReq;
import com.v1.video.domain.PayOrderEntity.PayOrder;
import com.v1.video.interfaces.OnPayListener;
import com.v1.video.util.Logger;

public class WeixinUtils {

	private static final String TAG = "WeixinUtils";
	private static OnPayListener mOnPayListener;

	public static OnPayListener getmOnPayListener() {
		return mOnPayListener;
	}

	public static void setmOnPayListener(OnPayListener mOnPayListener) {
		WeixinUtils.mOnPayListener = mOnPayListener;
	}

	public static String getProductArgs(String name, String money) {
		StringBuffer xml = new StringBuffer();
		try {
			String nonceStr = genNonceStr();
			xml.append("</xml>");
			List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
			packageParams.add(new BasicNameValuePair("appid", Key.WX_APP_ID));
			packageParams.add(new BasicNameValuePair("body", name));
			packageParams.add(new BasicNameValuePair("mch_id", Key.WX_MCH_ID));
			packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
			packageParams.add(new BasicNameValuePair("notify_url",
					"http://121.40.35.3/test"));
			packageParams.add(new BasicNameValuePair("out_trade_no",
					genOutTradNo()));
			packageParams.add(new BasicNameValuePair("spbill_create_ip",
					"127.0.0.1"));
			packageParams.add(new BasicNameValuePair("total_fee", money));
			packageParams.add(new BasicNameValuePair("trade_type", "APP"));
			String sign = getPackageSign(packageParams);
			packageParams.add(new BasicNameValuePair("sign", sign));
			String xmlstring = toXml(packageParams);
			return new String(xmlstring.getBytes(), "ISO8859-1");
		} catch (Exception e) {
			Logger.e(TAG, "getProductArgs fail, ex = " + e.getMessage());
			return null;
		}
	}

	private static String genNonceStr() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000))
				.getBytes());
	}

	private static long genTimeStamp() {
		return System.currentTimeMillis() / 1000;
	}

	private static String genOutTradNo() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000))
				.getBytes());
	}

	/**
	 * 生成签名
	 */

	private static String getPackageSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Key.WX_API_KEY);
		String packageSign = MD5.getMessageDigest(sb.toString().getBytes())
				.toUpperCase();
		Logger.i(TAG, "生成签名getPackageSign(): " + packageSign);
		return packageSign;
	}

	private static String toXml(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (int i = 0; i < params.size(); i++) {
			sb.append("<" + params.get(i).getName() + ">");
			sb.append(params.get(i).getValue());
			sb.append("</" + params.get(i).getName() + ">");
		}
		sb.append("</xml>");
		Logger.i(TAG, "toXml(): " + sb.toString());
		return sb.toString();
	}

	public static PayReq getPayReq(PayOrder payOrder) {
		PayReq req = new PayReq();
		req.appId = Key.WX_APP_ID;
		req.partnerId = payOrder.getPartnerid();
		req.prepayId = payOrder.getPrepayid();
		req.packageValue = payOrder.getPackageValue();
		req.nonceStr = payOrder.getNoncestr();
		req.timeStamp = payOrder.getTimeStamp();
		req.sign = payOrder.getSign();
		Logger.i(TAG, "签名信息getPayReq(): " + req.sign);
		return req;
	}

	private static String getAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Key.WX_API_KEY);
		// this.sb.append("sign str\n"+sb.toString()+"\n\n");
		String appSign = MD5.getMessageDigest(sb.toString().getBytes())
				.toUpperCase();
		Logger.e("orion", appSign);
		return appSign;
	}

	public static Map<String, String> decodeXml(String content) {
		try {
			Map<String, String> xml = new HashMap<String, String>();
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(new StringReader(content));
			int event = parser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {

				String nodeName = parser.getName();
				switch (event) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.START_TAG:
					if ("xml".equals(nodeName) == false) {
						// 实例化student对象
						xml.put(nodeName, parser.nextText());
					}
					break;
				case XmlPullParser.END_TAG:
					break;
				}
				event = parser.next();
			}
			return xml;
		} catch (Exception e) {
			Logger.e("orion", e.toString());
		}
		return null;
	}
}
